import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createServer } from 'node:http';
import { shell } from 'electron';

export * from '../utils'

export const getChromePath = () => {
  if (process.platform === 'win32') {
    return 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'
  } else {
    return '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
  }
}

export const getAvailablePort = async () => {
  return new Promise((resolve, reject) => {
    const server = createServer();
    server.unref();
    server.on('error', reject);
    server.listen(0, () => {
      const { port } = server.address();
      server.close(() => {
        resolve(port);
      });
    });
  });
}

export const getTempPath = () => {
  const tempDir = os.tmpdir();
  const logDir = path.join(tempDir, import.meta.env.VITE_APP_SHORT_NAME);
  if (!fs.existsSync(logDir)) {
    fs.mkdirSync(logDir);
  }
  return logDir;
}

export const getAppPath = () => {
  const documentsDir = path.join(os.homedir(), 'Documents');
  const appDir = path.join(documentsDir, import.meta.env.VITE_APP_SHORT_NAME);
  
  if (!fs.existsSync(appDir)) {
    fs.mkdirSync(appDir, { recursive: true });
  }

  return appDir;
}

export const getLogsPath = () => {
  const logDir = path.join(getTempPath(), 'logs');

  if (!fs.existsSync(logDir)) {
    fs.mkdirSync(logDir, { recursive: true });
  }

  return logDir;
}

export const openTempPath = () => {
  const tempPath = getTempPath();
  shell.openPath(tempPath)
}

export const openAppPath = () => {
  const appPath = getAppPath();
  shell.openPath(appPath)
}